package top.anonyeast.interceptor;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.anonyeast.config.Auth;
import top.anonyeast.util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT拦截器：检验请求是否合法
 */
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //直接放行OPTIONS请求
        if(HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            response.setStatus(response.SC_OK);
            return true;
        }
        Map<String,String> map = new HashMap<>();
        //从请求头中获取token
        String token = request.getHeader("Authorization");
        //验证令牌
        if(JwtUtil.checkToken(Auth.JWT_SEC,token)){
            //放行请求
            return true;
        }else {
            map.put("status","failed");
            map.put("msg","token无效");
            String json = JSON.toJSONString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(json);
            response.sendError(401);
            return false;
        }
    }
}
